package com.blue.core.dict.annotation;

import com.blue.core.file.ClassScanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 解析Dict
 *
 * @author zhengjin
 * @since 1.0 2018年12月03日
 */
public class DictPostProcessor implements BeanFactoryPostProcessor, InitializingBean
{
	private static final String BASE_PACKAGE = "com.blue.core.dict";
	private static Logger logger = LoggerFactory.getLogger(DictPostProcessor.class);

	private List<String> packageList;

	public DictPostProcessor()
	{
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
	{
		DictParser parser = DictParser.getInstance();
		logger.info("初始化 Dict 解析");
		String[] names = beanFactory.getBeanNamesForAnnotation(Dict.class);
		for (String name : names)
		{
			BeanDefinition definition = beanFactory.getBeanDefinition(name);
			definition.setLazyInit(true);
			try
			{
				Class<?> clazz = Class.forName(definition.getBeanClassName());
				parser.parse(clazz);
			}
			catch (ClassNotFoundException e)
			{
				e.printStackTrace();
			}
		}

	}

	public void setScanPackages(List<String> packageList)
	{
		this.packageList = packageList;
	}

	@Override
	public void afterPropertiesSet() throws Exception
	{
		if (packageList == null)
			packageList = new ArrayList<>();

		if (!packageList.contains(BASE_PACKAGE))
		{
			packageList.add(BASE_PACKAGE);
		}
		logger.info("扫描包：{}", packageList);

		ClassScanner scanner = new ClassScanner();
		scanner.setClassHandler(new DictClassHandler());
		scanner.scan(true, packageList);
	}
}
